package com.rp.demo.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rp.demo.commons.Constant;
import com.rp.demo.entity.MsgLog;
import com.rp.demo.mapper.MsgLogMapper;
import com.rp.demo.service.MsgLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 消息投递日志 服务实现类
 *
 * @author ruipeng
 * @since 2021-05-07
 */
@Slf4j
@Service
public class MsgLogServiceImpl implements MsgLogService {

    @Autowired
    private MsgLogMapper msgLogMapper;

    /**
     * 修改消息状态
     * @param msgId
     * @param status
     */
    @Override
    public void updateStatus(String msgId, int status) {
        MsgLog entity = new MsgLog();
        entity.setMsgId(msgId);
        entity.setStatus(status);
        int result = msgLogMapper.updateById(entity);
        log.info("修改消息状态result = {}",result);


    }


    /**
     * 查询所有投递中的消息
     * @return
     */
    @Override
    public List<MsgLog> selectTimeoutMsg() {
        QueryWrapper<MsgLog> query = new QueryWrapper<>();
        query.eq("status", Constant.MsgLogStatus.DELIVERING);
        query.ge("next_try_time",new Date());
        List<MsgLog> msgLogs = msgLogMapper.selectList(query);
        log.info("查询所有投递中的消息 msgLogs = {}", JSONUtil.toJsonStr(msgLogs));
        return msgLogs;
    }

    /**
     * 投递次数+1
     * @param msgId
     * @param nextTryTime
     */
    @Override
    public void updateTryCount(String msgId, Date nextTryTime) {
        MsgLog msgLog = msgLogMapper.selectById(msgId);
        msgLog.setTryCount(msgLog.getStatus() + 1);
        msgLog.setNextTryTime(nextTryTime);
        int updateById = msgLogMapper.updateById(msgLog);
        log.info("修改投递次数+1 返回结果 updateById = {}",updateById);
    }

    @Override
    public MsgLog selectByMsgId(String msgId) {
        return msgLogMapper.selectById(msgId);
    }
}
